<template>
    <a-modal
      v-model:open="modalOpen"
      title="找回密码"
      :width="500"
      :closable="true"
      :mask-closable="true"
      :mask="true"
      :z-index="1000"
      :centered="true"
      @cancel="handleCancel"
      @ok="handleCancel"
    >
      <div class="forgot-password-container">
              <a-steps :current="currentStep" size="small" class="steps">
        <a-step title="输入邮箱" />
        <a-step title="验证码验证" />
        <a-step title="重置密码" />
      </a-steps>

  
        <div v-if="currentStep === 0" class="step-content">
          <a-form :model="emailForm" layout="vertical">
            <a-form-item label="邮箱地址" name="email">
              <a-input
                v-model:value="emailForm.email"
                size="large"
                placeholder="请输入您的注册邮箱"
              >
                <template #prefix>
                  <MailOutlined />
                </template>
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-button
                type="primary"
                size="large"
                block
                @click="handleSendCode"
                :loading="sendingCode"
              >
                发送验证码
              </a-button>
            </a-form-item>
          </a-form>
        </div>
  
        <div v-if="currentStep === 1" class="step-content">
          <a-form :model="codeForm" layout="vertical">
            <a-form-item label="验证码" name="code">
              <a-input
                v-model:value="codeForm.code"
                size="large"
                placeholder="请输入6位验证码"
                maxlength="6"
              >
                <template #prefix>
                  <SafetyOutlined />
                </template>
              </a-input>
              <template #extra>
                <span class="code-tip">验证码已发送至 {{ emailForm.email }}，有效期5分钟</span>
              </template>
            </a-form-item>
            <a-form-item>
              <a-button
                type="primary"
                size="large"
                block
                @click="handleVerifyCode"
                :loading="verifyingCode"
              >
                验证
              </a-button>
            </a-form-item>
            <div class="resend-section">
              <span>没有收到验证码？</span>
              <a-button 
                type="link" 
                @click="handleResendCode"
                :disabled="countdown > 0"
              >
                {{ countdown > 0 ? `${countdown}秒后重发` : "重新发送" }}
              </a-button>
            </div>
          </a-form>
        </div>
  
        <div v-if="currentStep === 2" class="step-content">
          <a-form :model="passwordForm" layout="vertical">
            <a-form-item label="新密码" name="newPassword">
              <a-input-password
                v-model:value="passwordForm.newPassword"
                size="large"
                placeholder="请输入新密码"
              >
                <template #prefix>
                  <LockOutlined />
                </template>
              </a-input-password>
            </a-form-item>
            <a-form-item label="确认密码" name="confirmPassword">
              <a-input-password
                v-model:value="passwordForm.confirmPassword"
                size="large"
                placeholder="请再次输入新密码"
              >
                <template #prefix>
                  <LockOutlined />
                </template>
              </a-input-password>
            </a-form-item>
            <a-form-item>
              <a-button
                type="primary"
                size="large"
                block
                @click="handleResetPassword"
                :loading="resettingPassword"
              >
                重置密码
              </a-button>
            </a-form-item>
          </a-form>
        </div>
      </div>
    </a-modal>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive, computed, onUnmounted } from "vue"
  import { message } from "ant-design-vue"
  import { sendResetEmail, resetPasswordByEmail } from "@/api/user/authController"
  import { MailOutlined, SafetyOutlined, LockOutlined } from "@ant-design/icons-vue"
  
  interface Props {
    open: boolean
  }
  
  interface Emits {
    (e: "update:open", value: boolean): void
    (e: "reset-success"): void
  }
  
  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()
  
  const modalOpen = computed({
    get: () => props.open,
    set: (value: boolean) => emit("update:open", value)
  })
  
  const currentStep = ref(0)
  const sendingCode = ref(false)
  const verifyingCode = ref(false)
  const resettingPassword = ref(false)
  const countdown = ref(0)
  let countdownTimer: any | null = null
  
  const emailForm = reactive({ email: "" })
  const codeForm = reactive({ code: "" })
  const passwordForm = reactive({
    newPassword: "",
    confirmPassword: ""
  })
  
  const handleSendCode = async () => {
  try {
    sendingCode.value = true
    const result = await sendResetEmail({ email: emailForm.email })
    if ((result as any).code === "00000") {
      message.success("验证码已发送到您的邮箱")
      currentStep.value = 1
      startCountdown()
    } else {
      throw new Error((result as any).msg || "发送验证码失败")
    }
  } catch (error: any) {
    message.error(error.message || "发送验证码失败，请重试")
  } finally {
    sendingCode.value = false
  }
}
  
  const handleVerifyCode = async () => {
  try {
    verifyingCode.value = true
    if (!codeForm.code || codeForm.code.length !== 6 || !/^\d{6}$/.test(codeForm.code)) {
      message.error("请输入6位数字验证码")
      return
    }
    currentStep.value = 2
    message.success("验证码格式正确，请继续设置新密码")
  } catch (error: any) {
    message.error(error.message || "验证码验证失败，请重试")
  } finally {
    verifyingCode.value = false
  }
}
  
  const handleResetPassword = async () => {
    try {
      resettingPassword.value = true
      const result = await resetPasswordByEmail({
        email: emailForm.email,
        code: codeForm.code,
        newPassword: passwordForm.newPassword
      })
      if ((result as any).code === "00000") {
        emit("reset-success")
        handleCancel()
      } else {
        throw new Error((result as any).msg || "密码重置失败")
      }
    } catch (error: any) {
      message.error(error.message || "密码重置失败，请重试")
    } finally {
      resettingPassword.value = false
    }
  }
  
  const handleResendCode = async () => {
    if (countdown.value > 0) return
    try {
      sendingCode.value = true
      const result = await sendResetEmail({ email: emailForm.email })
      if ((result as any).code === "00000") {
        message.success("验证码已重新发送")
        startCountdown()
      } else {
        throw new Error((result as any).msg || "发送验证码失败")
      }
    } catch (error: any) {
      message.error(error.message || "发送验证码失败，请重试")
    } finally {
      sendingCode.value = false
    }
  }
  
  const startCountdown = () => {
    countdown.value = 60
    countdownTimer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(countdownTimer!)
        countdownTimer = null
      }
    }, 1000)
  }
  
  const handleCancel = () => {
    currentStep.value = 0
    emailForm.email = ""
    codeForm.code = ""
    passwordForm.newPassword = ""
    passwordForm.confirmPassword = ""
    if (countdownTimer) {
      clearInterval(countdownTimer)
      countdownTimer = null
    }
    countdown.value = 0
    emit("update:open", false)
  }
  
  onUnmounted(() => {
    if (countdownTimer) {
      clearInterval(countdownTimer)
    }
  })
  </script>
  
  <style scoped>
  .forgot-password-container {
    padding: 20px 0;
  }
  .steps {
    margin-bottom: 24px;
  }
  .step-content {
    min-height: 200px;
  }
  .code-tip {
    color: #666;
    font-size: 12px;
  }
  .resend-section {
    text-align: center;
    margin-top: 16px;
    color: #666;
  }
  .resend-section .ant-btn {
    padding: 0;
    height: auto;
    font-size: 12px;
  }
  </style>